// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html


import { NoticeSettlement } from "../bean/GameBean";
import { GlobalBean } from "../bean/GlobalBean";
import { EventType } from "../common/EventCenter";
import { GameMgr } from "../common/GameMgr";
import { AutoMessageBean, AutoMessageId } from "../net/MessageBaseBean";
import CongratsItemController from "../pfb/CongratsItemController";
import { Config } from "../util/Config";
import { Tools } from "../util/Tools";

const { ccclass, property } = cc._decorator;

//结算页面
@ccclass
export default class CongratsDialogController extends cc.Component {

    @property(cc.Node)
    boardBg: cc.Node = null
    @property(cc.Node)
    contentLay: cc.Node = null
    @property(cc.Node)
    backBtn: cc.Node = null
    @property(cc.Prefab)
    congratsItem: cc.Prefab = null;//列表的 item
    @property(cc.Node)
    public layoutNode: cc.Node = null;//存放列表的布局


    countdownTimeLabel: cc.Label = null
    countdownInterval: number = null;//倒计时的 id

    backCallback: Function = null //隐藏弹窗的回调
    seconds: number = 10;//倒计时 10 秒


    onLoad() {
        this.countdownTimeLabel = this.backBtn.getChildByName('buttonLabel_time').getComponent(cc.Label);
    }
    protected onEnable(): void {
        this.updateCountdownLabel(this.seconds);
        //Tools.setCountDownTimeLabel(this.backBtn)
    }

    start() {
        //backBtn 按钮点击事件
        Tools.greenButton(this.backBtn, () => {
            this.hide(true)
        })
        // 设置倒计时标签的固定位置
        this.setFixedCountdownPosition();

        // 设置整个按钮的点击效果（包括按钮背景和倒计时标签的统一反馈）
        this.setupButtonWithCountdownEffect();
    }


    show(noticeSettlement: NoticeSettlement, backCallback: Function) {
        this.backCallback = backCallback
        this.node.active = true
        this.boardBg.scale = 0
        // 每次显示时重新设置倒计时标签的固定位置，确保位置正确
        this.setFixedCountdownPosition();
        this._setData(noticeSettlement)
        // 执行缩放动画
        cc.tween(this.boardBg)
            .to(Config.dialogScaleTime, { scale: 1 })
            .start();
    }

    _setData(noticeSettlement: NoticeSettlement) {

        const index = noticeSettlement.users.findIndex((item) => item.userId === GlobalBean.GetInstance().loginData.userInfo.userId);//搜索
        GlobalBean.GetInstance().loginData.userInfo.coin = noticeSettlement.users[index].coin //更新自己的最新金币

        this.layoutNode.removeAllChildren();
        for (let i = 0; i < noticeSettlement.users.length; ++i) {
            const item = cc.instantiate(this.congratsItem);
            const data = noticeSettlement.users[i];
            this.layoutNode.addChild(item);
            setTimeout(() => {
                // 砖块派对游戏使用noticeStartGame中的users数据
                const gameUsers = GlobalBean.GetInstance().noticeStartGame?.users || [];
                item.getComponent(CongratsItemController).createData(data, gameUsers);
            }, 100);
        }
        this.startCountdown(10)//倒计时 10 秒
    }

    // bool 在隐藏的时候是否返回大厅
    hide(bool: boolean = false) {
        if (this.backCallback) {
            this.backCallback()
        }
        GameMgr.Console.Log('隐藏结算页面')
        // 执行缩放动画
        cc.tween(this.boardBg)
            .to(Config.dialogScaleTime, { scale: 0 })
            .call(() => {
                this.node.active = false
                if (bool) {
                    GlobalBean.GetInstance().cleanData()
                    let autoMessageBean: AutoMessageBean = {
                        'msgId': AutoMessageId.JumpHallPage,//跳转进大厅页面
                        'data': { 'type': 2 }//2是结算弹窗跳转的
                    }
                    GameMgr.Event.Send(EventType.AutoMessage, autoMessageBean);
                }
            })
            .start();
    }
    protected onDisable(): void {
        if (this.countdownInterval) {
            clearInterval(this.countdownInterval);
        }

    }

  

    startCountdown(seconds: number) {
        // 在开始倒计时前再次确保位置正确
        this.setFixedCountdownPosition();
        let remainingSeconds = seconds;
        this.updateCountdownLabel(remainingSeconds);

        this.countdownInterval = setInterval(() => {
            remainingSeconds--;

            if (remainingSeconds <= 0) {
                clearInterval(this.countdownInterval);
                this.countdownInterval = null
                // 倒计时结束时的处理逻辑
                this.hide(true)
                return
            }
            this.updateCountdownLabel(remainingSeconds);
        }, 1000);
    }

    updateCountdownLabel(seconds: number) {
        if (this.countdownTimeLabel) {
            this.countdownTimeLabel.string = `（${seconds}s）`;
            // 每次更新倒计时文本后，重新设置位置，确保位置始终正确
            this.scheduleOnce(() => {
                this.setFixedCountdownPosition();
            }, 0.01);
        }
    }

    // 设置固定的倒计时位置，左括号始终对准back文字的右边
    private setFixedCountdownPosition() {
        if (!this.backBtn) {
            console.warn("CongratsDialogController: setFixedCountdownPosition - backBtn不存在");
            return;
        }

        // 重新获取节点，确保引用是最新的
        let btn = this.backBtn.getChildByName('button_label');
        let timeBtn = this.backBtn.getChildByName('buttonLabel_time');

        if (!btn || !timeBtn) {
            console.warn("CongratsDialogController: setFixedCountdownPosition - 缺少子节点", {
                hasBtn: !!btn,
                hasTimeBtn: !!timeBtn
            });
            return;
        }

        // 重新获取倒计时标签组件，确保引用正确
        this.countdownTimeLabel = timeBtn.getComponent(cc.Label);
        if (!this.countdownTimeLabel) {
            console.warn("CongratsDialogController: setFixedCountdownPosition - 无法获取Label组件");
            return;
        }

        // 延迟一帧执行，确保所有UI初始化完成
        this.scheduleOnce(() => {
            // 强制设置锚点为左对齐，确保左括号位置固定
            timeBtn.anchorX = 0;
            timeBtn.anchorY = 0.5; // 确保垂直居中

            // 计算固定位置：back文字右边缘 + 小间距，左括号固定在此位置
            let fixedLeftPos = btn.position.x + btn.width / 2 - 10; // 5像素间距

            // 直接设置位置
            timeBtn.setPosition(fixedLeftPos, 0);

            // 再次强制设置锚点，防止被其他代码重置
            timeBtn.anchorX = 0;
            timeBtn.anchorY = 0.5;

        }, 0.01);
    }

    // 设置整个按钮的统一点击效果（按钮背景和倒计时标签都有反馈）
    private setupButtonWithCountdownEffect() {
        if (!this.backBtn) {
            console.warn("CongratsDialogController: backBtn未设置，无法添加点击效果");
            return;
        }

        // 获取按钮的子节点
        const btnColorNormal = this.backBtn.getChildByName('btn_color_normal');
        const buttonLabel = this.backBtn.getChildByName('button_label');

        if (!btnColorNormal || !buttonLabel) {
            console.warn("CongratsDialogController: 按钮结构不完整，无法添加点击效果");
            return;
        }

        const label = buttonLabel.getComponent(cc.Label);
        const labelOutline = buttonLabel.getComponent(cc.LabelOutline);

        if (!label || !labelOutline) {
            console.warn("CongratsDialogController: 按钮标签组件不完整");
            return;
        }

        // 记录倒计时标签的原始字体大小
        let originalCountdownFontSize = 36;
        let originalCountdownLineHeight = 36;
        if (this.countdownTimeLabel) {
            originalCountdownFontSize = this.countdownTimeLabel.fontSize;
            originalCountdownLineHeight = this.countdownTimeLabel.lineHeight;
        }

        // 自定义按钮点击效果，同时控制倒计时标签
        Tools.setTouchEvent(btnColorNormal,
            // 按下时：按钮和倒计时标签都变暗
            (node: cc.Node) => {
                // 按钮背景变暗
                Tools.setNodeSpriteFrame(node, Config.btnGreenPressed);

                // 按钮文字变暗
                label.fontSize = 34;
                label.lineHeight = 34;
                let color = new cc.Color();
                cc.Color.fromHEX(color, Config.btnGreenPressedColor);
                labelOutline.color = color;
                buttonLabel.color = cc.Color.fromHEX(new cc.Color(), '#B3B3B3');

                // 倒计时标签也变暗（字体缩小效果）
                if (this.countdownTimeLabel && this.countdownTimeLabel.node) {
                    // 字体大小缩小（从原始大小缩小2）
                    this.countdownTimeLabel.fontSize = originalCountdownFontSize - 2;
                    this.countdownTimeLabel.lineHeight = originalCountdownLineHeight - 2;

                    // 轮廓颜色变化（如果有LabelOutline组件）
                    const countdownOutline = this.countdownTimeLabel.getComponent(cc.LabelOutline);
                    if (countdownOutline) {
                        let outlineColor = new cc.Color();
                        cc.Color.fromHEX(outlineColor, Config.btnGreenPressedColor);
                        countdownOutline.color = outlineColor;
                    }

                    // 文字颜色变暗
                    this.countdownTimeLabel.node.color = cc.Color.fromHEX(new cc.Color(), '#B3B3B3');
                }
            },
            // 抬起时：恢复正常并执行点击逻辑
            (node: cc.Node) => {
                // 按钮背景恢复
                Tools.setNodeSpriteFrame(node, Config.btnGreenNormal);

                // 按钮文字恢复
                label.fontSize = 36;
                label.lineHeight = 36;
                let color = new cc.Color();
                cc.Color.fromHEX(color, Config.btnGreenNormalColor);
                labelOutline.color = color;
                buttonLabel.color = cc.Color.fromHEX(new cc.Color(), '#FFFFFF');

                // 倒计时标签恢复（恢复到原始大小）
                if (this.countdownTimeLabel && this.countdownTimeLabel.node) {
                    // 字体大小恢复到原始大小
                    this.countdownTimeLabel.fontSize = originalCountdownFontSize;
                    this.countdownTimeLabel.lineHeight = originalCountdownLineHeight;

                    // 轮廓颜色恢复（如果有LabelOutline组件）
                    const countdownOutline = this.countdownTimeLabel.getComponent(cc.LabelOutline);
                    if (countdownOutline) {
                        let outlineColor = new cc.Color();
                        cc.Color.fromHEX(outlineColor, Config.btnGreenNormalColor);
                        countdownOutline.color = outlineColor;
                    }

                    // 文字颜色恢复
                    this.countdownTimeLabel.node.color = cc.Color.fromHEX(new cc.Color(), '#FFFFFF');
                }

                // 执行点击逻辑
                this.hide(true);
            },
            // 取消时：恢复正常
            (node: cc.Node) => {
                // 按钮背景恢复
                Tools.setNodeSpriteFrame(node, Config.btnGreenNormal);

                // 按钮文字恢复
                label.fontSize = 36;
                label.lineHeight = 36;
                let color = new cc.Color();
                cc.Color.fromHEX(color, Config.btnGreenNormalColor);
                labelOutline.color = color;
                buttonLabel.color = cc.Color.fromHEX(new cc.Color(), '#FFFFFF');

                // 倒计时标签恢复（恢复到原始大小）
                if (this.countdownTimeLabel && this.countdownTimeLabel.node) {
                    // 字体大小恢复到原始大小
                    this.countdownTimeLabel.fontSize = originalCountdownFontSize;
                    this.countdownTimeLabel.lineHeight = originalCountdownLineHeight;

                    // 轮廓颜色恢复（如果有LabelOutline组件）
                    const countdownOutline = this.countdownTimeLabel.getComponent(cc.LabelOutline);
                    if (countdownOutline) {
                        let outlineColor = new cc.Color();
                        cc.Color.fromHEX(outlineColor, Config.btnGreenNormalColor);
                        countdownOutline.color = outlineColor;
                    }

                    // 文字颜色恢复
                    this.countdownTimeLabel.node.color = cc.Color.fromHEX(new cc.Color(), '#FFFFFF');
                }
            }
        );
    }
}
